package org.springframework.security.samples.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @author Webster
 * <p>
 * Description:配置类
 * </p>
 * @date 2021/3/10
 * @see org.springframework.security.samples.config
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
				.authorizeRequests((authorize) -> authorize
						.antMatchers("/css/**", "/index").permitAll()
						.antMatchers("/user/**").hasRole("USER")
				)
				.formLogin((formLogin) -> formLogin
						.loginPage("/login")
						.failureUrl("/login-error")
						.successForwardUrl("/user/index")
						.usernameParameter("username")
						.passwordParameter("password")
						.permitAll()
				)
				.logout(logout -> logout
								.logoutUrl("/logout")
								.logoutSuccessUrl("/index")
								//.logoutSuccessHandler(logoutSuccessHandler)
								.invalidateHttpSession(true)
						//.addLogoutHandler(logoutHandler)
						//.deleteCookies(cookieNamesToClear)
				);
	}

	@Bean
	public UserDetailsService users() {
		UserDetails user = User.builder()
				.username("user")
				.password("password")
				.roles("USER")
				.build();
		UserDetails admin = User.builder()
				.username("admin")
				.password("password")
				.roles("USER", "ADMIN")
				.build();
		return new InMemoryUserDetailsManager(user, admin);
	}

}
